package MasterManagers.SocketManager;

import MasterManagers.TableManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import io.netty.util.internal.SocketUtils;
//import javafx.scene.layout.Region;
import lombok.extern.slf4j.Slf4j;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

/**
 * 客户端线程，和客户端通信
 */
@Slf4j
public class SocketThread implements Runnable{
    private boolean is_Running = false;
    private Socket socket;
    private TableManager tableManager;
    public BufferedReader input = null;
    public PrintWriter output = null;
    private ClientCMD clientCMD;
    private RegionCMD regionCMD;

    public SocketThread(Socket socket, TableManager tableManager) throws IOException{
        this.tableManager = tableManager;
        this.socket = socket;
        this.is_Running = true;
        this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.output = new PrintWriter(socket.getOutputStream(), true);
        this.clientCMD = new ClientCMD(tableManager, socket);
        this.regionCMD = new RegionCMD(tableManager, socket);

        System.out.println("Create new client thread:" + socket.getInetAddress() +":"+ socket.getPort());
    }

    public void run() {
        String line;
        try{
            while(is_Running){
                Thread.sleep(Long.parseLong("1000"));
                line = input.readLine();
                if(line != null)
                    this.processCmd(line);
            }
        }
//        catch ( InterruptedException | IOException e){
//            e.printStackTrace();
//        }
        catch(InterruptedException | IOException e) {
            System.out.println("Connection closed");
        }
//        finally {
//            if(socket != null) {
//                try {
//                    socket.close();
//                    String hostUrl = socket.getInetAddress().getHostAddress();
//                    tableManager.deleteServer(hostUrl);
//                    tableManager.deleteClient(hostUrl);
//                } catch(IOException e) { /* ignored */ }
//            }
//        }
    }

    public void processCmd(String cmd){
        String result = "";
        if(cmd.startsWith("<C2M>")) {
            System.out.println("Receive from Client: "+cmd);
            result = clientCMD.processClientCommand(cmd);
        }
        else if(cmd.startsWith("<R2M>")) {
            System.out.println("Receive from Region: "+cmd);
            result = regionCMD.processRegionCommand(cmd);
        }

        if(!result.equals("")){//发给对应的ip
            this.send(result);
        }
    }

    public void send(String result){
        output.println(result);
    }

}
